package ar.com.photo_admin.service.security

import grails.plugins.springsecurity.SpringSecurityService
import javax.servlet.ServletException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import org.springframework.security.authentication.AuthenticationServiceException
import org.springframework.security.core.Authentication
import org.springframework.security.core.AuthenticationException
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter

class FacebookAuthenticationProcessingFilter extends  AbstractAuthenticationProcessingFilter {
	
	def grailsApplication
	
	FacebookService facebookService
	SpringSecurityService springSecurityService

	final String FACEBOOK_SECURITY_FORM_ACCESS_TOKEN_KEY = "j_facebook_token"

	FacebookAuthenticationProcessingFilter() {
		super("/j_facebook_security_check")
	}

//	void afterPropertiesSet() {
//		super.setFilterProcessesUrl(grailsApplication.config.facebook.security.filter.url)
//	}

	Authentication attemptAuthentication(HttpServletRequest request,  HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
		if (!request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod())
		}

		String accessToken = request.getParameter(FACEBOOK_SECURITY_FORM_ACCESS_TOKEN_KEY)
		
		def profile = facebookService.getProfileByAccesToken(accessToken)
		if (profile)
			return this.getAuthenticationManager().authenticate(new FacebookAuthenticationToken(profile.id, accessToken))

		return null;
	}
}